/* 
 * File:   JWorkerThread.cpp
 * Author: johnneyshi
 * 
 * Created on 2013年3月6日, 上午10:25
 */

#include "JWorkerThread.h"
#include "JDefine.h"
#include <pthread.h>
#include "JLog.h"
#include <sys/syscall.h>
#include <iostream>

using namespace std;

#define gettid() syscall(__NR_gettid)

//extern pthread_mutex_t adapterConnFdMutex = PTHREAD_MUTEX_INITIALIZER;
//extern pthread_cond_t adapterConnFdCond = PTHREAD_COND_INITIALIZER;

JWorkerThread::JWorkerThread(JServerWorker* _w,bool _isPermanent) : pWorker(_w),clientFd(-1),isPermanent(_isPermanent)
{
    
}


JWorkerThread::~JWorkerThread() 
{
}

void JWorkerThread::Start()
{
    JLog::Log(JLogMessage,"Create thread,pid:%d\n",gettid());
    do
    {
        GetClientFd();
        DealMsg();
    }while(isPermanent);
}

void JWorkerThread::GetClientFd()
{
    pthread_mutex_lock(&JServerWorker::adapterConnFdMutex);
    while(pWorker->needDealFds.empty())
    {
        pthread_cond_wait(&JServerWorker::adapterConnFdCond,&JServerWorker::adapterConnFdMutex);
    }
    clientFd = pWorker->needDealFds.front();
    pWorker->needDealFds.pop();
    pthread_mutex_unlock(&JServerWorker::adapterConnFdMutex);
    JLog::Log(JLogMessage,"thread,pid:%d get fd:%d\n",gettid(),clientFd);
}

void JWorkerThread::DealMsg()
{
    cout << "JWorkerThread DealMsg()" << endl;
    while((n = read(clientFd,buff,BUFF_SIZE)) > 0)
    {
        buff[n] = '\0';
        JLog::Log(JLogMessage,"pid:%d msg:%s\n",gettid(),buff);
        write(clientFd,buff,n);
    }
    if(n == 0)
    {
        JLog::Log(JLogMessage,"pid:%d n=0\n",gettid());
    }
    else if(n == -1)
    {
        JLog::Log(JLogMessage,"pid:%d n=-1\n",gettid());
    }
}


